<template>
  <div class="dept-management">
    <div class="page-header">
      <h2>{{ $t('common.deptManagement') }}</h2>
      <p>{{ $t('common.deptManagementDescription') }}</p>
    </div>
    
    <div class="search-container">
      <div class="search-item">
        <label>{{ $t('dept.deptName') }}:</label>
        <InputText v-model="searchParams.deptName" placeholder="{{ $t('common.pleaseInput') }}" />
      </div>
      <div class="search-item">
        <label>{{ $t('dept.status') }}:</label>
        <Dropdown
          v-model="searchParams.status"
          :options="statusOptions"
          placeholder="{{ $t('common.pleaseSelect') }}"
          optionValue="value"
          optionLabel="label"
        />
      </div>
      <div class="search-actions">
        <Button @click="search" icon="pi pi-search">{{ $t('common.search') }}</Button>
        <Button @click="reset" icon="pi pi-refresh">{{ $t('common.reset') }}</Button>
        <Button @click="handleAdd" icon="pi pi-plus" severity="success">{{ $t('common.add') }}</Button>
      </div>
    </div>
    
    <div class="table-container">
      <DataTable
        :value="deptStore.getDeptList"
        :loading="deptStore.getLoading"
        :paginator="true"
        :rows="searchParams.pageSize"
        :first="(searchParams.page - 1) * searchParams.pageSize"
        :totalRecords="deptStore.getDeptTotal"
        @page="onPageChange"
        @sort="onSortChange"
      >
        <Column field="id" header="{{ $t('dept.deptId') }}" sortable></Column>
        <Column field="deptName" header="{{ $t('dept.deptName') }}" sortable>
          <template #body="{ data }">
            <div :style="{ paddingLeft: `${(data.level || 0) * 20}px` }">{{ data.deptName }}</div>
          </template>
        </Column>
        <Column field="parentId" header="{{ $t('dept.parentId') }}" sortable></Column>
        <Column field="orderNum" header="{{ $t('dept.orderNum') }}" sortable></Column>
        <Column field="status" header="{{ $t('common.status') }}">
          <template #body="{ data }">
            <Badge :severity="data.status === 1 ? 'success' : 'danger'">
              {{ data.status === 1 ? $t('common.active') : $t('common.inactive') }}
            </Badge>
          </template>
        </Column>
        <Column field="createTime" header="{{ $t('common.createTime') }}" sortable></Column>
        <Column header="{{ $t('common.operate') }}" style="width: 15rem">
          <template #body="{ data }">
            <Button @click="handleAdd(data)" icon="pi pi-plus-circle" size="small" severity="info"></Button>
            <Button @click="handleEdit(data)" icon="pi pi-pencil" size="small"></Button>
            <Button @click="handleDelete(data.id)" icon="pi pi-trash" size="small" severity="danger"></Button>
          </template>
        </Column>
      </DataTable>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <Dialog v-model:visible="dialogVisible" :header="dialogTitle" :modal="true" :style="{ width: '500px' }">
      <div class="form-container">
        <div class="form-item">
          <label>{{ $t('dept.parentDept') }}:</label>
          <Dropdown
            v-model="formData.parentId"
            :options="deptTree"
            placeholder="{{ $t('common.pleaseSelect') }}"
            optionValue="id"
            optionLabel="deptName"
            :filter="true"
            :disabled="formData.parentId === '0'"
          />
        </div>
        <div class="form-item">
          <label>{{ $t('dept.deptName') }} *:</label>
          <InputText v-model="formData.deptName" />
        </div>
        <div class="form-item">
          <label>{{ $t('dept.orderNum') }} *:</label>
          <InputNumber v-model="formData.orderNum" min="1" :max="999" />
        </div>
        <div class="form-item">
          <label>{{ $t('dept.status') }} *:</label>
          <Dropdown
            v-model="formData.status"
            :options="statusOptions"
            optionValue="value"
            optionLabel="label"
          />
        </div>
        <div class="form-item">
          <label>{{ $t('dept.leader') }}:</label>
          <InputText v-model="formData.leader" />
        </div>
        <div class="form-item">
          <label>{{ $t('dept.phone') }}:</label>
          <InputText v-model="formData.phone" />
        </div>
        <div class="form-item">
          <label>{{ $t('dept.email') }}:</label>
          <InputText v-model="formData.email" />
        </div>
      </div>
      <template #footer>
        <Button @click="dialogVisible = false">{{ $t('common.cancel') }}</Button>
        <Button @click="handleSave" severity="primary">{{ $t('common.submit') }}</Button>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDeptStore } from '../../../store/modules/system/dept'
import type { Department } from '../../../types/app.d'
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import InputNumber from 'primevue/inputnumber'
import Dropdown from 'primevue/dropdown'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Badge from 'primevue/badge'
import Dialog from 'primevue/dialog'

const { t } = useI18n()
const deptStore = useDeptStore()

// 搜索参数
const searchParams = reactive({
  page: 1,
  pageSize: 10,
  deptName: '',
  status: null as number | null
})

// 状态选项
const statusOptions = [
  { label: t('common.active'), value: 1 },
  { label: t('common.inactive'), value: 0 }
]

// 部门树数据
const deptTree = ref<Department[]>([])

// 对话框状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('')
const parentId = ref<string>('')

// 表单数据
const formData = reactive<Partial<Department>>({
  deptName: '',
  parentId: '0',
  orderNum: 0,
  status: 1,
  leader: '',
  phone: '',
  email: ''
})

// 初始化
const init = () => {
  deptStore.getDeptListAction(searchParams)
  loadDeptTree()
}

// 加载部门树
const loadDeptTree = async () => {
  const treeData = await deptStore.getDeptTreeAction()
  if (treeData) {
    // 构建树结构，确保顶层节点显示
    const rootNode: Department = { id: '0', deptName: t('common.rootDept'), parentId: '-1', orderNum: 0, status: 1 }
    deptTree.value = [rootNode, ...treeData]
  }
}

// 搜索
const search = () => {
  searchParams.page = 1
  deptStore.getDeptListAction(searchParams)
}

// 重置
const reset = () => {
  Object.assign(searchParams, {
    page: 1,
    pageSize: 10,
    deptName: '',
    status: null
  })
  deptStore.getDeptListAction(searchParams)
}

// 页面变化
const onPageChange = (event: any) => {
  searchParams.page = event.page + 1
  searchParams.pageSize = event.rows
  deptStore.getDeptListAction(searchParams)
}

// 排序变化
const onSortChange = (event: any) => {
  // 实际项目中可以根据排序字段和方向进行排序
  deptStore.getDeptListAction(searchParams)
}

// 添加部门
const handleAdd = (parent?: Department) => {
  isEdit.value = false
  dialogTitle.value = t('common.add') + t('common.dept')
  Object.assign(formData, {
    deptName: '',
    parentId: parent?.id || '0',
    orderNum: 0,
    status: 1,
    leader: '',
    phone: '',
    email: ''
  })
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = async (dept: Department) => {
  isEdit.value = true
  dialogTitle.value = t('common.edit') + t('common.dept')
  await deptStore.getDeptInfoAction(dept.id)
  if (deptStore.getCurrentDept) {
    Object.assign(formData, deptStore.getCurrentDept)
  }
  dialogVisible.value = true
}

// 保存部门
const handleSave = async () => {
  if (isEdit.value && formData.id) {
    const success = await deptStore.updateDeptAction(formData.id, formData)
    if (success) {
      dialogVisible.value = false
      deptStore.getDeptListAction(searchParams)
      deptStore.clearCurrentDept()
      loadDeptTree()
    }
  } else {
    const success = await deptStore.createDeptAction(formData as Omit<Department, 'id' | 'createTime' | 'updateTime'>)
    if (success) {
      dialogVisible.value = false
      deptStore.getDeptListAction(searchParams)
      loadDeptTree()
    }
  }
}

// 删除部门
const handleDelete = async (id: string) => {
  // 检查是否有子部门
  const hasChildren = deptStore.getDeptList.some(dept => dept.parentId === id)
  if (hasChildren) {
    alert(t('dept.hasChildrenCannotDelete'))
    return
  }
  
  if (confirm(t('common.confirmDelete'))) {
    const success = await deptStore.deleteDeptAction(id)
    if (success) {
      deptStore.getDeptListAction(searchParams)
      loadDeptTree()
    }
  }
}

// 初始化加载数据
init()
</script>

<style scoped>
.dept-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-container {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: flex-end;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.search-item label {
  font-weight: 500;
  color: #333;
}

.search-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-item label {
  font-weight: 500;
  color: #333;
}

.form-item input,
.form-item select,
.form-item .p-inputnumber {
  width: 100%;
}
</style>